package com.demo.service.impl;


import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.demo.entity.constants.Constants;
import com.demo.entity.enums.CommentsStatusEnum;
import com.demo.entity.enums.ResponseCodeEnum;
import com.demo.entity.po.Comment;

import com.demo.entity.po.PostInfo;
import com.demo.entity.query.CommentQuery;

import com.demo.entity.vo.PaginationResultVO;

import com.demo.exception.BusinessException;
import com.demo.service.CommentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.demo.entity.query.SimplePage;

import com.demo.mappers.CommentMapper;

import com.demo.entity.enums.PageSize;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description:评论表serviceImpl
 * @Date:2025-03-01
 * @author：author
*/
@Service("commentService")
public class CommentServiceImpl implements CommentService {

	@Resource
	private CommentMapper<Comment, CommentQuery> commentMapper;
	@Autowired
	private PostInfoServiceImpl postInfoService;

	/**
	 * 根据条件查询列表
	 */
	public List<Comment> findListByParam(CommentQuery query) {
		return this.commentMapper.selectList(query);
	}

	/**
	 * 根据条件查询数量
	 */
	public Integer findCountByParam(CommentQuery query) {
		return this.commentMapper.selectCount(query);
	}

	/**
	 * 分页查询
	 */
	public PaginationResultVO<Comment> findListByPage(CommentQuery query) {
		int count = this.findCountByParam(query);
		int pageSize = query.getPageSize() == null ? PageSize.SIZE15.getSize() : query.getPageSize();
		SimplePage page = new SimplePage(query.getPageNo(), count, pageSize);
		query.setSimplePage(page);
		List<Comment> list = this.findListByParam(query);
		return new PaginationResultVO(count, page.getPageSize(), page.getPageNo(), page.getPageTotal(), list);
	}

	/**
	 * 新增
	 */
	public Integer add(Comment bean) {
		return this.commentMapper.insert(bean);
	}

	/**
	 * 批量新增
	 */
	public Integer addBatch(List<Comment> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.commentMapper.insertBatch(listBean);
	}

	/**
	 * 批量新增或者修改
	 */
	public Integer addOrUpdateBatch(List<Comment> listBean) {
		if (listBean == null || listBean.isEmpty()) {
			return 0;
		}
		return this.commentMapper.insertOrUpdateBatch(listBean);
	}

	/**
	 * 根据CommentId查询
	 */
	public Comment getCommentByCommentId(Long commentId) {
		return this.commentMapper.selectByCommentId(commentId);
	}

	/**
	 * 根据CommentId更新
	 */
	public Integer updateCommentByCommentId(Comment bean, Long commentId) {
		return this.commentMapper.updateByCommentId(bean, commentId);
	}

	/**
	 * 根据CommentId删除
	 */
	public Integer deleteCommentByCommentId(Long commentId) {
		return this.commentMapper.deleteByCommentId(commentId);
	}


	/**
	 * 保存评论
	 *
	 * @param comments
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveComments(Comment comments) {
		PostInfo posts = postInfoService.getPostsById(comments.getPostId());
		if (posts == null) {
			throw new BusinessException("帖子不存在或已经被删除");
		}
		posts.setCommentCount(posts.getCommentCount() + Constants.ONE);
		postInfoService.updatePostInfoByPostId(posts, posts.getPostId());
		comments.setCreateTime(new Date());
		comments.setUpdateTime(new Date());
		comments.setStatus(CommentsStatusEnum.ABLE.getStatus());
		this.commentMapper.insert(comments);
	}


	@Override
	public List<Comment> findCommentsList(CommentQuery query) {
		// 设置查询条件，按照 created_at 字段降序排列（最新评论在前）
		query.setOrderBy("create_time desc");

		// 调用 commentMapper 的 selectList 方法，根据查询条件获取所有符合条件的评论列表
		List<Comment> comments = commentMapper.selectList(query);

		// 按 parentId 分组：将所有评论按其父评论 ID (parentCommentId) 进行分组
		// 过滤掉 parentCommentId 为 null 的评论，因为它们是顶级评论，不需要归入任何分组
		Map<Long, List<Comment>> commentMap = comments.stream()
				.filter(comment -> comment.getParentCommentId() != null) // 筛选出有父评论的评论
				.collect(Collectors.groupingBy(Comment::getParentCommentId)); // 按 parentCommentId 分组

		// 遍历所有评论，为每个评论设置其子评论（replies）
		comments.forEach(comment -> {
			if (commentMap.containsKey(comment.getCommentId())) {
				// 如果当前评论的 commentId 存在于 commentMap 中，说明它有子评论
				comment.setReplies(commentMap.get(comment.getCommentId())); // 设置子评论列表
			} else {
				// 如果当前评论没有子评论，则设置为空列表
				comment.setReplies(Collections.emptyList());
			}
		});

		// 返回顶级评论（parentId 为 null 的评论）
		return comments.stream()
				.filter(comment -> comment.getParentCommentId() == null) // 筛选出顶级评论
				.collect(Collectors.toList()); // 将筛选结果收集为列表并返回
	}


	/**
	 * 删除评论
	 * @param userId
	 * @param commentId
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delComment(Long userId, Long commentId) {
		Comment commentDB = commentMapper.selectByCommentId(commentId);
		if (commentDB== null) {
			throw new BusinessException("评论不存在或已经被删除");
		}
		if (!commentDB.getUserId().equals(userId)) {
			throw new BusinessException(ResponseCodeEnum.CODE_600);
		}
		// 更新评论数量
		PostInfo postInfo =	new  PostInfo();
		postInfo.setCommentCount(postInfo.getCommentCount() - Constants.ONE);
		postInfoService.updatePostInfoByPostId(postInfo, postInfo.getPostId());
	}
}